package basis

/**
 *
 *   @project kotlin-docs
 *   @datetime 2020/9/27 14:44
 *
 */
fun main() {
    //ifDemo()
    //whenDemo()
    //forDemo()
    foo()
}

fun ifDemo() {
    var max = 10
    if(max < 100)
        println(max)
    else
        println(100)

    val a = 10
    val b = 20
    val aOrb = if(a > b) a else b
    println("aOrb = $aOrb")

    val maxab = if(a > b) {
        print("choose a")
    } else {
        print("choose b")
        println()
    }
    println("maxab = $maxab")

    val maxab1 = if(a > b) {
        print("choose a")
        a
    } else {
        print("choose b")
        println()
        b
        999
    }
    println("maxab = $maxab1")


}

fun whenDemo() {
    val x = 1
    when(x) {
        1 -> println("x == 1")
        2 -> println("x == 2")
        else -> {
            println("x is neither 1 nor 2")
        }
    }

    when(x) {
        1,2 -> println("x == 1 or x == 2")
        else -> {
            println("x is neither 1 nor 2")
        }
    }
}

fun forDemo() {
    val arr = Array(3){3};
    for(i in arr) {
        print("$i ")
    }
    println()
    for(i in arr.indices) {
        println("index=$i, value=${arr[i]}")
    }
    for ((index, value) in arr.withIndex()) {
        println("the element at $index is $value")
    }
    println()
    for(i in 1..10){
        print("$i  ")
    }
    println()
    for(i in 10 downTo 0 step 2){
        print("$i  ")
    }
    println()
}

fun foo() {
    foo1()
    foo2()
    foo3()
    foo4()
}

fun foo1() {
    listOf(1,2,3,4,5).forEach{
        if(it == 3)
            return
        println(it)
    }
    println("this point is unreachable")
}

fun foo2() {
    listOf(1,2,3,4,5).forEach label@{
        if(it == 3)
            return@label
        println(it)
    }
    println(" done with explicit label")
}

fun foo3() {
    listOf(1,2,3,4,5).forEach{
        if(it == 3)
            return@forEach
        println(it)
    }
    println(" done with implicit label")
}

fun foo4() {
    listOf(1,2,3,4,5).forEach(fun(value: Int) {
        if(value == 3) {
            return
        }
        println(value)
    })
    println(" done with anonymous function")
}